import {StyleSheet, Text, TouchableOpacity, View, TextInput} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import NoData from "@/components/NoData";
import FcButton from "@/components/FcButton";
import FcModal from '@/components/FcModal';
import DatePicker from '@/components/DatePicker';
import {Flex} from "@ant-design/react-native";

import {
  useGetPayListQuery,
} from "@/store/api/contentManage/contentManageApi";

import {
  useGetDeptTreeListQuery,
} from "@/store/api/login/loginApi";

type Props = {}

const recharge = (props: Props) => {
  const [listParams, setListParams] = useState({
    pageNo: 1,
    pageSize: 20,
    username: '',
    updateTime_begin: '',
    updateTime_end: '',
  })

  const [payList, setPayList] = useState<any>([])
  const [realNameList, setRealNameList] = useState<any>([])
  const [realNameOpen, setRealNameOpen] = useState(false)
  const [dateOpen, setDateOpen] = useState(false)
  const [searchText, setSearchText] = useState<any>('')
  const [isCheckAll, setIsCheckAll] = useState<any>(false)
  const [pageScrollBodyH, setPageScrollBodyH] = useState(0)

  const {data:listDataRef,isSuccess:listSuccess,refetch:listRefetch} = useGetPayListQuery(listParams)
  const {data:deptListDataRef,isSuccess:deptListSuccess} = useGetDeptTreeListQuery({depType: 2})

  useEffect(() => {
    if(listDataRef?.code === 200){
      const list = listDataRef?.result?.records || []
      setPayList(list)
    }
  },[listSuccess,listDataRef])

  useEffect(() => {
    if(deptListDataRef?.code === 0){
      let list = deptListDataRef?.result || []
      let arr:any = []

      list.forEach((main:any) => {
        forEachEmpList(main, arr);
      })
      setRealNameList(arr)
    }
  },[deptListDataRef,deptListSuccess])

  //获取组件架构
  const forEachEmpList = (obj:any, arr:any) => {
    obj.empList.forEach((user:any) => {
      arr.push({label:user.realname,value:user.id});
    })
    if(obj.children && obj.children.length > 0) {
      obj.children.forEach((child:any) => {
        forEachEmpList(child, arr);
      })
    }
  }

  //弹窗搜索
  const handleSearchChange = (val:any) => {
    setSearchText(val)
    
    let arr = JSON.parse(JSON.stringify(realNameList)).filter((item:any) => item.label.includes(val))

    if(arr.length == 0) return

    let flag = true
    for(let i in arr){
      if(!arr[i].checked){
        flag = false
        break;
      }
    }

    setIsCheckAll(flag)
  }

  //全选
  const handleCheckAll = () => {
    let arr = JSON.parse(JSON.stringify(realNameList))
    
    if(searchText){
      arr.forEach((item:any) => {
        if(item.label.includes(searchText)){
          item.checked = !isCheckAll
        }
      });
    }else{
      arr.forEach((item:any) => {
        item.checked = !isCheckAll
      });
    }

    setIsCheckAll(!isCheckAll)
    setRealNameList(arr)
  }

  //筛选弹窗单选
  const handleCheckItem = (item:any, index:any) => {
    let arr = JSON.parse(JSON.stringify(realNameList))

    if(searchText){
      arr.forEach((val:any) => {
        if(val.label.includes(searchText) && val.value == item.value){
          val.checked = !val.checked
        }
      });

      setIsCheckAll(true)

      for(let i in arr){
        if(arr[i].label.includes(searchText)){
          if(!arr[i].checked){
            setIsCheckAll(false)
            break;
          }
        }
      }
    }else{
      arr[index].checked = !arr[index].checked

      setIsCheckAll(true)

      for(let i in arr){
        if(!arr[i].checked){
          setIsCheckAll(false)
          break;
        }
      }
    }

    setRealNameList(arr)
  }

  const handleSubmit = () => {
    let arr = realNameList.filter((val:any) => val.checked).map((item: any) => item.label)

    setRealNameOpen(false)
    setListParams({
      ...listParams,
      pageNo: 1,
      username: arr.join()
    })

    listRefetch()
  }

  const getScrollBodyInfo = ({height}) => {
    setPageScrollBodyH(height)
  }

  return (
    <PageScrollView
      isTransparentTab
      getPageScrollBodyInfo={getScrollBodyInfo}
      pageTab={
        <PageTabBar
          style={{marginVertical: 10}}
          title={'充值记录'}
        />
      }
    >
      <View>
        <Flex justify='between'>
          <TouchableOpacity style={{width: '48%'}} onPress={() => setRealNameOpen(true)}>
            <Flex justify='center' style={styles.search_item}>
              <Text style={styles.search_item_text} numberOfLines={1}>
                {realNameList.filter((val:any) => val.checked)?.[0]?.label ||'用户名'}
                </Text>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe647;</Text>
            </Flex>
          </TouchableOpacity>

          <TouchableOpacity style={{width: '48%'}} onPress={() => setDateOpen(true)}>
            <Flex justify='center' style={styles.search_item}>
              <Text style={styles.search_item_text} numberOfLines={1}>交易时间</Text>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe647;</Text>
            </Flex>
          </TouchableOpacity>
        </Flex>

        {
          payList.map((item:any, index:any) => (
            <View key={index} style={styles.pay_item}>
              <Flex justify='between' style={{paddingHorizontal: 12}}>
                <Text style={{fontWeight: '500', fontSize: 15}}>{item.sourceTypeName}</Text>
                <Text style={{color: '#FA5151'}}>- ¥{(item.amount / 100).toFixed(2)}</Text>
              </Flex>
              <View style={styles.dashed}></View>
              <Text style={styles.pay_item_label}>用户名：<Text style={styles.pay_item_value}>{item.username}</Text></Text>
              <Text style={styles.pay_item_label}>商户订单号：<Text style={styles.pay_item_value}>{item.orderNo}</Text></Text>
              <Text style={styles.pay_item_label}>微信支付单号：<Text style={styles.pay_item_value}>{item.payOrderNo || '--'}</Text></Text>
              <Text style={styles.pay_item_label}>交易时间：<Text style={styles.pay_item_value}>{item.creatTime}</Text></Text>
              <Text style={styles.pay_item_label}>交易状态：
                <Text style={{color: item.tradeState == 0 ? '#FA5151' : item.tradeState == 1 ? '#07C160' : item.tradeState == -1 ? '#FA5151' : '#000'}}>
                  {item.tradeState == 0 ? '未支付' : item.tradeState == 1 ? '支付成功' : item.tradeState == -1 ? '支付失败' : '已关闭'}
                </Text>
              </Text>
            </View>
          ))
        }
        {payList.length == 0 && <Flex style={{height: pageScrollBodyH - 50}}><NoData hintText='暂无充值记录'/></Flex>}

        {/* 使用人弹窗 */}
        <FcModal
          isOpen={realNameOpen}
          onFcModalClose={() => setRealNameOpen(false)}
          titleText='使用人'
          header={
            <TouchableOpacity>
              <View style={styles.search_wrap}>
                <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 7}}>&#xe641;</Text>
                <TextInput 
                  style={styles.search} 
                  placeholder={'请输入要搜索内容'} 
                  placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                  onChangeText={(val) => handleSearchChange(val)}
                  value={searchText}
                />
              </View>
            </TouchableOpacity>
          }
          titleBottomBorderWidth={0}
          bottom={
            <View style={styles.modal_bottom}>
              <Flex>
                <TouchableOpacity style={[styles.select_icon, isCheckAll && styles.select_active]} onPress={() => handleCheckAll()}>
                  {isCheckAll && <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                </TouchableOpacity>
                <Text>全选</Text>
              </Flex>
                
              <FcButton
                onClick={() => handleSubmit()}
                type='BjJB'
                colors={['#6989FF', '#C65EFD']}
                style={{width: 88, height: 32, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='确认选择'
              />
            </View>
          }
        >
          <View style={{paddingHorizontal: 16}}>
            {
              realNameList.filter((val:any) => val.label.includes(searchText)).length == 0 ?
              <View style={{flexDirection: 'column',alignItems: 'center',justifyContent: 'center',paddingTop: 60,paddingBottom: 120}}>
                <NoData hintText='暂无数据'/>
              </View>
              :
              realNameList.filter((val:any) => val.label.includes(searchText)).map((item:any, index:any) => (
                <Flex justify='between' key={index} style={styles.modal_item}>
                  <Flex>
                    <TouchableOpacity style={[styles.select_icon, item.checked && styles.select_active]} onPress={() => handleCheckItem(item, index)}>
                      {item.checked && <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                    </TouchableOpacity>
                    <Text>{ item.label }</Text>
                  </Flex>
                </Flex>
              ))
            }
          </View>
        </FcModal>

        {/* 日期弹窗 */}
        <DatePicker
          isOpen={dateOpen} 
          titleText={'交易时间'} 
          dateRange={[listParams.updateTime_begin, listParams.updateTime_end]}
          dateType='range'
          onClose={() => setDateOpen(false)}
          onConfirm={(startDate:any, endDate:any) => {setListParams({...listParams, pageNo: 1, updateTime_begin: startDate, updateTime_end: endDate}); listRefetch()}}
        ></DatePicker>
      </View>
    </PageScrollView>
  )
}

export default recharge

const styles = StyleSheet.create({
  search_item: {
    height: 28,
    borderRadius: 4,
    backgroundColor: '#FFF',
  },
  search_item_text: {
    color: 'rgba(0, 0, 0, 0.5)',
    fontSize: 12,
    marginLeft: 2,
    maxWidth: '85%',
  },
  pay_item: {
    paddingVertical: 12,
    borderRadius: 8,
    backgroundColor: '#FFF',
    marginTop: 8,
  },
  dashed: {
    borderBottomWidth: 1,
    borderBottomColor: '#D8D8D8',
    borderStyle: 'dashed',
    marginVertical: 10,
  },
  pay_item_label: {
    color: 'rgba(0, 0, 0, 0.3)',
    lineHeight: 30,
    fontSize: 13,
    paddingHorizontal: 12,
  },
  pay_item_value: {
    color: 'rgba(0, 0, 0, 0.7)',
    lineHeight: 30,
    fontSize: 12
  },
  search_wrap: {
    flexDirection: 'row',
    alignItems: "center",
    backgroundColor: '#F1F2F4',
    borderRadius: 9,
    marginHorizontal: 16,
    height: 40,
    paddingHorizontal: 14,
  },
  search: {
    flex: 1,
    height: '100%',
    color: 'rgba(0,0,0,0.9)'
  },
  modal_bottom: {
    height: 72,
    display: 'flex',
    flexDirection: "row",
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
  },
  modal_item: {
    height: 56,
    borderRadius: 8,
    borderBottomWidth: 1,
    borderColor: 'rgba(0, 0, 0, 0.1)',
  },
  select_icon: {
    width: 20,
    height: 20,
    borderRadius: '50%',
    borderWidth: 1,
    borderColor: 'rgba(0,0,0,0.5)',
    marginRight: 12,
  },
  select_active: {
    borderColor: '#2856FF',
    backgroundColor: '#2856FF',
    flexDirection: 'row',
    alignItems: "center",
    justifyContent: "center"
  },
})

